//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <aura.h>


Aura_Handle g_hMutex;

void threadfuncWaitMutex(Aura_PVoid pArg)
{
    Aura_ThreadId iThreadId;
    Aura_WaitResult result;
    Aura_ECode ec;

    AuraThread_GetCurrentId(&iThreadId);
    while(1){
        Aura_printf("****id:%d****time out:%d*****\n", iThreadId, (Aura_Millisecond)pArg);
        ec = AuraMutex_Lock(g_hMutex, (Aura_Millisecond)pArg, &result);
        if(AURA_FAILED(ec)){
            Aura_printf("AURA_FAILED lock thread id:%d.\n", iThreadId);
            return;
        }
        if(Aura_WaitResult_OK != result){
            Aura_printf("Thread:%d time out.\n", iThreadId);
            AuraThread_Sleep(1000, &result);
            continue;
        }
        Aura_printf("Enter the mutex thread id:%d.\n", iThreadId);
        AuraMutex_Unlock(g_hMutex);
    }
    return ;
}

int AuraTest_MutexTimeOut()
{
    Aura_Handle hThread[2];
    Aura_ThreadId iThreadId;
    Aura_WaitResult result;
    int i = 0;
    Aura_ECode ec;

    ec = AuraThread_GetCurrentId(&iThreadId);

	if (AURA_FAILED(ec)) {
        Aura_printf(" <AuraThread_GetCurrentId> failed. (ec = 0x%x)\n", ec);
        goto ErrorExit;
	}


    ec = AuraMutex_Create(AURA_NULL, AURA_FALSE, &g_hMutex);
	if (AURA_FAILED(ec)) {
        Aura_printf(" <AuraMutex_Create> failed. (ec = 0x%x)\n", ec);
        goto ErrorExit;
	}

    ec = AuraMutex_Lock(g_hMutex, AURA_INFINITE, &result);
		if (AURA_FAILED(ec)) {
        Aura_printf(" <AuraMutex_Create> failed. (ec = 0x%x)\n", ec);
        goto ErrorExit;
	}

    for(i = 0; i < 2; i++){
        ec = AuraThread_Create(
            threadfuncWaitMutex,
            (Aura_PVoid)(i*5000 + 1000),
            0,
            &hThread[i],
            AURA_NULL);
        if(AURA_FAILED(ec)){
            Aura_printf("^^^^^^^^^^^^^^^^^^^^^%d\n", i);
        }
    }

    ec = AuraMutex_Unlock(g_hMutex);
	if (AURA_FAILED(ec)) {
        Aura_printf(" <AuraMutex_Unlock> failed. (ec = 0x%x)\n", ec);
        goto ErrorExit;
	}

    for(i = 0; i < 2; i++){
        ec = AuraThread_Abort(hThread[i], 1);
	    if (AURA_FAILED(ec)) {
            Aura_printf(" <AuraThread_Abort> failed. (ec = 0x%x)\n", ec);
            goto ErrorExit;
	    }

        ec = AuraThread_Destroy(hThread[i]);
	    if (AURA_FAILED(ec)) {
            Aura_printf(" <AuraThread_Abort> failed. (ec = 0x%x)\n", ec);
            goto ErrorExit;
	    }
    }

    ec = AuraMutex_Destroy(g_hMutex);
	if (AURA_FAILED(ec)) {
        Aura_printf(" <AuraThread_Abort> failed. (ec = 0x%x)\n", ec);
        goto ErrorExit;
	}
    return AURA_TRUE;

ErrorExit:
	return AURA_FALSE;

}

